package com.joker.airoleplayplatformback.controller;


import com.joker.airoleplayplatformback.domain.entity.R;
import com.joker.airoleplayplatformback.service.OssService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 阿里云OSS上传接口
 *
 * @author Joker
 * @since 2023/10/12
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/1.0/oss")
@Validated
@Tag(name = "oss", description = "图片上传")
public class OssController {

    private final OssService ossService;

    /**
     * 上传图片接口
     *
     * @param file 图片文件
     * @return 图片访问URL
     */
    @Operation(summary = "上传图片", description = "上传图片文件到阿里云OSS，返回图片访问链接")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<String> uploadImage(@Parameter(description = "文件", required = true) @RequestParam("file") @NotNull MultipartFile file) {

        log.info("开始上传图片: {}", file.getOriginalFilename());

        try {

            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return R.error(400, "图片文件大小不能超过10MB");
            }

            // 上传图片到OSS
            String imageUrl = ossService.uploadImage(file);

            log.info("图片上传成功: {}", imageUrl);
            return R.ok(imageUrl);

        } catch (Exception e) {
            log.error("图片上传失败: {}", e.getMessage(), e);
            return R.error(500, "图片上传失败: " + e.getMessage());
        }
    }

}
